package com.terrence.filemgr.mgr.impl.ftp;

import java.io.InputStream;

import com.terrence.filemgr.FileMgrException;
import com.terrence.filemgr.mgr.AbsFileMgr;
import com.terrence.filemgr.mgr.AbsFileMgrContext;
import com.terrence.filemgr.mgr.vo.DirVo;

/**
 * 
 * @author wuchuang
 *
 * 2016年11月11日 下午2:57:15
 * 
 * FTP实现
 */
public class FTPMgr extends AbsFileMgr {
	
	private FTPContext context = null;
	
	public FTPMgr(AbsFileMgrContext context){
		super(context);
		this.context = (FTPContext)context;
	}
	
	@Override
	public String upload(InputStream inputStream, String fileRelativeDir,String fileName) throws FileMgrException {
		FTPUtil ftp = FTPUtil.getInstance(context);
		try{
			fileRelativeDir = (null == fileRelativeDir?"":fileRelativeDir);
			String fileRelativePath = ftp.uploadFile(inputStream, fileRelativeDir,fileName);
			return fileRelativePath;
		}catch(Exception ex){
			throw new FileMgrException(ex);
		}
	}
	
	@Override
	public String upload(InputStream inputStream, String fileType) throws FileMgrException {
		FTPUtil ftp = FTPUtil.getInstance(context);
		try{
			String fileRelativePath = ftp.uploadFile(inputStream, fileType);
			return fileRelativePath;
		}catch(Exception ex){
			throw new FileMgrException(ex);
		}
	}
	
	@Override
	public InputStream download(String fileRelativePath) throws FileMgrException {
		FTPUtil ftp = FTPUtil.getInstance(context);
		InputStream inputStream = null;
		try{
			inputStream = ftp.download(context.getBaseDir()+fileRelativePath);
			return inputStream;
		}catch(Exception ex){
			throw new FileMgrException(ex);
		}
	}
	@Override
	public Boolean remove(String fileRelativePath) throws FileMgrException {
		FTPUtil ftp = FTPUtil.getInstance(context);
		try{
			return ftp.remove(context.getBaseDir()+fileRelativePath);
		}catch(Exception ex){
			throw new FileMgrException(ex);
		}
	}

	@Override
	public void createDir(String relativePath,String dirName) throws FileMgrException {
		try {
			relativePath = (null == relativePath ? "":relativePath);
			dirName = (null == dirName ? "" : dirName);
			FTPUtil ftp = FTPUtil.getInstance(context);
			ftp.createDir(context.getBaseDir()+context.getPathSeperator()+relativePath+context.getPathSeperator()+dirName);
		} catch (Exception e) {
			throw new FileMgrException(e);
		}
	}
	
	@Override
	public Boolean isDirValid(String dirPath) throws FileMgrException{
		FTPUtil ftp = FTPUtil.getInstance(context);
		try {
			return ftp.isDirValid(dirPath);
		} catch (Exception e) {
			throw new FileMgrException(e);
		}
	}
	
	@Override
	public DirVo getDirStructures(String relativePath) throws FileMgrException {
		try {
			FTPUtil ftp = FTPUtil.getInstance(context);
			return ftp.getDirStructures(relativePath);
		} catch (Exception e) {
			throw new FileMgrException(e);
		}
	}
}
